package cn.liziguo.randomfilegenerator;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.function.DoubleConsumer;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE = 1024;

    private EditText editTextText1;
    private Spinner spinner;
    private EditText editTextText2;
    private ProgressBar progressBar;
    private Switch aSwitch;
    private Button button;

    private RandomFileFactory randomFileFactory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });
        // 不息屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        editTextText1 = findViewById(R.id.editTextText1);
        spinner = findViewById(R.id.spinner);
        editTextText2 = findViewById(R.id.editTextText2);
        progressBar = findViewById(R.id.progressBar1);
        aSwitch = findViewById(R.id.switch1);
        button = findViewById(R.id.button);
        TextView textView5 = findViewById(R.id.textView5);


        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, new String[]{"GB", "MB", "KB"});
        spinner.setAdapter(arrayAdapter);

        aSwitch.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b && !isSDCardAvailable()) {
                Toast.makeText(this, "sd卡不可用", Toast.LENGTH_SHORT).show();
                aSwitch.setChecked(false);
                return;
            }
            textView5.setText("生成文件所在路径: " + getDir(b).getAbsolutePath());
        });
        textView5.setText("生成文件所在路径: " + getDir(aSwitch.isChecked()).getAbsolutePath());

        button.setOnClickListener(view -> {
            if (randomFileFactory == null && aSwitch.isChecked()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    // 先判断有没有权限
                    if (Environment.isExternalStorageManager()) {
                        performFileOperations();
                    } else {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                    return;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 先判断有没有权限
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                            ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        performFileOperations();
                    } else {
                        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
                    }
                    return;
                }
            }
            if (randomFileFactory == null && aSwitch.isChecked() && !isSDCardAvailable()) {
                Toast.makeText(this, "sd卡不可用", Toast.LENGTH_SHORT).show();
                return;
            }
            performFileOperations();
        });
    }

    private void performFileOperations() {
        if (randomFileFactory == null) {
            long rate;
            switch ((String) spinner.getSelectedItem()) {
                case "GB":
                    rate = 1024 * 1024 * 1024;
                    break;
                case "MB":
                    rate = 1024 * 1024;
                    break;
                case "KB":
                    rate = 1024;
                    break;
                default:
                    throw new RuntimeException();
            }
            double fileSize = Double.parseDouble(editTextText1.getText().toString());
            int count = Integer.parseInt(editTextText2.getText().toString());
            DoubleConsumer onProgress = p -> {
                int progress = (int) (p * 100);
                if (progressBar.getProgress() == progress) {
                    return;
                }
                progressBar.setProgress(progress, true);
            };
            DoubleConsumer onSpeed = speed -> {
                String unit = "B";
                if (speed > 1024 * 1024 * 1024) {
                    speed /= 1024 * 1024 * 1024;
                    unit = "GB";
                } else if (speed > 1024 * 1024) {
                    speed /= 1024 * 1024;
                    unit = "MB";
                } else if (speed > 1024) {
                    speed /= 1024;
                    unit = "KB";
                }
                String str = String.format(Locale.CHINA, "停止 %5.2f%s/s", speed, unit);
                runOnUiThread(() -> button.setText(str));
            };
            Runnable onFinish = () -> {
                runOnUiThread(() -> {
                    randomFileFactory = null;
                    button.setText("开始");
                });
            };
            randomFileFactory = new RandomFileFactory(getDir(aSwitch.isChecked()), (long) (fileSize * rate), count, onProgress, onSpeed, onFinish);
            progressBar.setProgress(0);
            button.setText("停止 0.0B/s");
            new Thread(() -> {
                try {
                    randomFileFactory.create();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        } else {
            randomFileFactory.stop();
            randomFileFactory = null;
            button.setText("开始");
        }

    }


    private File getDir(boolean b) {
        // Android 10 改变了文件的存储方式不允许应用随意创建文件夹了，要用安卓提供的文件夹，提供的文件夹如下 @see: android.os.Environment
        if (b) {
            return new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOCUMENTS + "/random_file");
        }
        return getFilesDir();
    }

    public boolean isSDCardAvailable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被允许
                Toast.makeText(this, "权限被允许", Toast.LENGTH_SHORT).show();
                performFileOperations();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void logs() {

        // /data/user/0/com.google.myapplication/files
        String TAG = "RandomFileFactoryActivity";
        Log.d(TAG, "new File(\"\").getAbsolutePath() = " + new File("").getAbsolutePath());

        Log.d(TAG, "getContext().getFilesDir().getAbsolutePath() = " + getBaseContext().getFilesDir().getAbsolutePath());

        // /data/user/0/com.google.myapplication/files
        Log.d(TAG, "getContext().getFilesDir().getPath() = " + getBaseContext().getFilesDir().getPath());


        // /storage/emulated/0
        Log.d(TAG, "Environment.getExternalStorageDirectory() = " + Environment.getExternalStorageDirectory());


        // /data/user/0/com.google.myapplication
        Log.d(TAG, "getFilesDir().getParent() = " + getFilesDir().getParent());


        //  /data/user/0/com.google.myapplication/files
        Log.d(TAG, "getFilesDir() = " + getFilesDir());


        //  /storage/emulated/0/Android/data/com.google.myapplication/files
        Log.d(TAG, "getExternalFilesDir(null).getAbsolutePath() = " + getExternalFilesDir(null).getAbsolutePath());


        //  /storage/emulated/0/Android/data/com.google.myapplication/files/my
        Log.d(TAG, "getExternalFilesDir('my').getAbsolutePath() = " + getExternalFilesDir("my").getAbsolutePath());


        //   mounted
        Log.d(TAG, "Environment.getExternalStorageState() = " + Environment.getExternalStorageState());


        //   /storage/emulated/0/Download
        Log.d(TAG, "Environment.getExternalStoragePublicDirectory() = " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));

    }
}